# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo

class BaiduNewsPipeline(object):

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        if spider.name == "search":
            ret_dic = dict(item)
            _key = ret_dic['_key']
            _name = ret_dic['_name']
            del(ret_dic['_key'])
            del(ret_dic['_name'])
            if not self.db["baidu_news_search"].find_one({'_id':ret_dic['url'],'search_key': _key, "search_name": _name}):
                self.db["baidu_news_search"].update_one({'_id':ret_dic['url']},
                            {'$set':ret_dic,'$addToSet': {'search_key': _key, "search_name": _name}},upsert=True)
        elif spider.name == "pages":
            ret_dic = dict(item)
            self.db["news_page"].update_one({'_id': ret_dic['url']}, {'$set': ret_dic}, upsert=True)
            self.db['baidu_news_search'].update_one({'_id': ret_dic['url']}, {'$set': {'get_source': True}})
        return item